// pages/setUser/setUser.js
var util = require('../../utils/util.js');
const app = getApp();
const db = wx.cloud.database();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    avatarUrl: '', //用户头像
    openid: '', //openid
    nickName: '', //用户昵称
    isLogin: false, //默认未登录
    userData: {}, //用户信息
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //是否登录
    var isLogin = wx.getStorageSync('isLogin');
    if (isLogin) {
      this.setData({
        isLogin: true,
        openid: wx.getStorageSync('openid'),
        avatarUrl: wx.getStorageSync('avatarUrl'),
        nickName: wx.getStorageSync('nickName'),
        userData: wx.getStorageSync('userData'),
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  //输入用户昵称
  shuruNickName: function (event) {
    this.setData({
      nickName: event.detail.value
    })
  },

  //保存用户资料(成功即登录成功)
  save: function () {
    var that = this;
    //头像是否填写
    if (!that.data.avatarUrl) {
      wx.showToast({
        title: '请上传头像',
        icon: "none",
        duration: 1000
      })
      return;
    }
    //昵称是否填写
    if (!that.data.nickName) {
      wx.showToast({
        title: '请设置昵称',
        icon: "none",
        duration: 1000
      })
      return;
    }
    //提示框
    wx.showModal({
      title: '系统提示',
      content: '确认保存吗？',
      success: function (sm) {
        if (sm.confirm) {
          //用户点击了确定
          that.saveInfo();
        } else if (sm.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },


  //上传图片
  upload: function () {
    var that = this;
    //此处上传用户头像
    let orderCode = '';
    // 6位随机数(加在时间戳后面)
    for (var i = 0; i < 24; i++) {
      orderCode += Math.floor(Math.random() * 10);
    }
    //文件名
    const cloudPath = 'avatar/ ' + util.timestampToTimeFramt(new Date().getTime()) + '/' + (new Date().getTime() + orderCode) + '.png';
    //检测文本值
    return new Promise((resolve, reject) => {
      //上传图片云函数
      wx.cloud.callFunction({
        name: "upload",
        data: {
          cloudPath: cloudPath,
          avatarUrl: that.data.avatarUrl,
        },
        success: function (res) {
          resolve(res);
        },
        fail: function (res) {
          reject(res);
        }
      });
    })
  },


  //保存用户信息
  saveInfo: async function () {
    var that = this;
    //弹窗
    wx.showToast({
      title: '保存中',
      icon: "loading",
      duration: 30000
    })
    //先检测用户昵称
    const checkResult = await that.checkText();
    if (checkResult.result.errcode == 0) {
      //上传用户头像
      const uploadResult = await that.upload();
      //头像链接
      var fileID = uploadResult.result.fileID;
      //上传成功
      if (fileID) {
        //此处云开发函数注册用户
        wx.cloud.callFunction({
          name: 'login',
          data: {
            create_time: util.formatTime(new Date()),
            avatarUrl: fileID,
            nickName: that.data.nickName,
            openid: that.data.openid,
          }
        }).then((res) => {
          //登录成功跳转首页
          that.jump();
        }).catch((err) => {
          //登录失败
          wx.showToast({
            icon: 'none',
            title: '登录失败' + err
          })
        });
      } else {
        wx.showToast({
          title: '头像保存失败',
          icon: "none",
          duration: 1000
        })
      }
    } else {
      //清空用户昵称
      that.setData({
        nickName: ''
      })
      //不合法
      wx.showToast({
        title: '昵称不合法，请重新输入',
        icon: "none",
        duration: 1000
      })
    }
  },

  //跳转首页
  jump: function () {
    //保存成功
    wx.showToast({
      title: '保存成功',
      icon: 'success',
      mask: true,
      duration: 1000
    });
    //登录态
    wx.setStorageSync('isLogin', true);
    wx.setStorageSync('avatarUrl', this.data.avatarUrl);
    wx.setStorageSync('nickName', this.data.nickName);
    wx.setStorageSync('openid', this.data.openid);
    //延迟跳转
    setTimeout(function () {
      wx.navigateBack({
        delta: 1
      })
    }, 1000)
  },




  //检测文本
  checkText: function () {
    var that = this;
    //检测文本值
    return new Promise((resolve, reject) => {
      wx.cloud.callFunction({
        name: "checkText",
        data: {
          openid: that.data.openid,
          content: that.data.nickName
        },
        success: function (res) {
          resolve(res);
        },
        fail: function (res) {
          reject(res);
        }
      });
    })
  },


})